<template>
  <div class="marketplace-container">
    <div class="header">
      <h1>🏪 NFT 市场</h1>
      <el-button @click="loadMarketNFTs" :loading="loading" type="primary">
        刷新
      </el-button>
    </div>

    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>

    <div v-else-if="nfts.length === 0" class="empty-state">
      <el-empty description="暂无上架的 NFT">
        <el-button type="primary" @click="$router.push('/mint')">
          铸造第一个 NFT
        </el-button>
      </el-empty>
    </div>

    <div v-else class="nft-grid">
      <el-card 
        v-for="nft in nfts" 
        :key="nft.tokenId" 
        class="nft-card"
        shadow="hover"
      >
        <div class="nft-image-container">
          <img :src="getNFTImage(nft)" alt="NFT" class="nft-image" />
        </div>
        
        <div class="nft-info">
          <h3>{{ getNFTName(nft) }}</h3>
          <p class="nft-description">{{ getNFTDescription(nft) }}</p>
          
          <el-divider />
          
          <div class="nft-details">
            <div class="detail-item">
              <span class="label">Token ID:</span>
              <span class="value">#{nft.tokenId}</span>
            </div>
            <div class="detail-item">
              <span class="label">卖家:</span>
              <span class="value">{{ formatAddress(nft.seller) }}</span>
            </div>
            <div class="detail-item">
              <span class="label">价格:</span>
              <span class="value price">{{ nft.price }} ETH</span>
            </div>
          </div>

          <el-button 
            type="primary" 
            @click="handleBuy(nft)" 
            :loading="buying === nft.tokenId"
            :disabled="nft.seller.toLowerCase() === account?.toLowerCase()"
            style="width: 100%; margin-top: 15px"
          >
            {{ nft.seller.toLowerCase() === account?.toLowerCase() ? '这是你的 NFT' : '购买' }}
          </el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import web3Service from '../services/web3Service';

export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: 'Marketplace',
  setup() {
    const nfts = ref([]);
    const loading = ref(false);
    const buying = ref(null);
    const account = ref(null);

    const formatAddress = (address) => {
      if (!address) return '';
      return `${address.substring(0, 6)}...${address.substring(address.length - 4)}`;
    };

    const getNFTImage = (nft) => {
      try {
        const metadata = parseTokenURI(nft.tokenURI);
        return metadata?.image || 'https://via.placeholder.com/300?text=NFT';
      } catch {
        return 'https://via.placeholder.com/300?text=NFT';
      }
    };

    const getNFTName = (nft) => {
      try {
        const metadata = parseTokenURI(nft.tokenURI);
        return metadata?.name || `NFT #${nft.tokenId}`;
      } catch {
        return `NFT #${nft.tokenId}`;
      }
    };

    const getNFTDescription = (nft) => {
      try {
        const metadata = parseTokenURI(nft.tokenURI);
        return metadata?.description || '暂无描述';
      } catch {
        return '暂无描述';
      }
    };

    const parseTokenURI = (tokenURI) => {
      if (tokenURI.startsWith('data:application/json;base64,')) {
        const base64Data = tokenURI.replace('data:application/json;base64,', '');
        return JSON.parse(atob(base64Data));
      }
      return null;
    };

    const loadMarketNFTs = async () => {
      if (!web3Service.getAccount()) {
        ElMessage.warning('请先连接钱包');
        return;
      }

      try {
        loading.value = true;
        account.value = web3Service.getAccount();
        nfts.value = await web3Service.getMarketNFTs();
      } catch (error) {
        ElMessage.error(error.message || '加载失败');
      } finally {
        loading.value = false;
      }
    };

    const handleBuy = async (nft) => {
      try {
        await ElMessageBox.confirm(
          `确定要购买这个 NFT 吗？价格: ${nft.price} ETH`,
          '确认购买',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          }
        );

        buying.value = nft.tokenId;
        await web3Service.buyNFT(nft.tokenId, nft.price);
        ElMessage.success('购买成功!');
        
        // 刷新列表
        await loadMarketNFTs();
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error(error.message || '购买失败');
        }
      } finally {
        buying.value = null;
      }
    };

    onMounted(() => {
      if (web3Service.getAccount()) {
        loadMarketNFTs();
      }
    });

    return {
      nfts,
      loading,
      buying,
      account,
      formatAddress,
      getNFTImage,
      getNFTName,
      getNFTDescription,
      loadMarketNFTs,
      handleBuy
    };
  }
};
</script>

<style scoped>
.marketplace-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 2rem;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
}

.header h1 {
  margin: 0;
  color: #303133;
}

.loading-container {
  padding: 2rem;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.nft-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 2rem;
}

.nft-card {
  transition: transform 0.3s;
}

.nft-card:hover {
  transform: translateY(-5px);
}

.nft-image-container {
  width: 100%;
  height: 300px;
  overflow: hidden;
  border-radius: 8px;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nft-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.nft-info {
  padding: 1rem 0;
}

.nft-info h3 {
  margin: 0 0 0.5rem 0;
  color: #303133;
  font-size: 1.2rem;
}

.nft-description {
  color: #606266;
  font-size: 0.9rem;
  margin: 0;
  line-height: 1.5;
  max-height: 3em;
  overflow: hidden;
  text-overflow: ellipsis;
}

.nft-details {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-item .label {
  color: #909399;
  font-size: 0.9rem;
}

.detail-item .value {
  color: #303133;
  font-weight: 500;
}

.detail-item .price {
  color: #67c23a;
  font-size: 1.2rem;
  font-weight: bold;
}
</style>

